<?php

namespace app\admin\controller\m;

use app\common\controller\Backend;
use think\Collection;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 物料库存
-物料收发存
 *
 * @icon fa fa-circle-o
 */
class Stock extends Backend
{

    /**
     * Stock模型对象
     * @var \app\admin\model\m\Stock
     */
    protected $model = null;

    //  大厂权限      @wtt
    protected $dataLimitCom = "auth";       // 默认: false,  'auth':  强制验证厂区权限 ( 表示显示当前厂区数据 )
    protected $dataCompanyField = "factory_id";     // 厂区权限字段

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\m\Stock;
        $this->view->assign("statusList", $this->model->getStatusList());

        $factory =  new \app\admin\model\Factory ;
        $info =  new \app\admin\model\m\Info ;
        $this->assignconfig("factoryList", $factory->getList());
        $this->view->assign("factoryList", $factory->getList());
        $this->assignconfig("infoList", $info->getList());

    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $infoModel = new \app\admin\model\m\Stockbill;
        // id="c-admin_ids" data-source="auth/admin/index" data-params='{"custom[factory_id]":"1"}'  data-field="nickname"

        // ok
        // 添加筛选条件,  限制本厂管理员,  方法 selectpage

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        // 厂区独立数据
        // do  汇总 stockbill表数据,  显示即时库存
        if( $this->auth->factory_id > 0 ){
//            $list = $infoModel->alias("a")
//                ->field("a.*, i.name as info_name ")
//                ->join("m_info i ON i.id=a.info_id", 'left')
//                ->where('a.factory_id' ,'eq', $this->auth->factory_id )
//                ->where('a.status' ,'eq', '已通过' )
//                ->select();

            $list = $infoModel
                ->field("*, 0 as sum")
                ->where('factory_id' ,'eq', $this->auth->factory_id )
                ->where('status' ,'eq', '已通过' )
                ->where($where)
                ->select();

            $infos = array_column( Collection($list)->toArray() , null, 'info_id');
            //print_r($infos); die;
            //  todo  优化计算方法
            foreach($list as $k => $v){
                $infos[ $v['info_id'] ]['sum'] += $v['nums'];
            }
        } else {
            // todo  总管理看每个厂区或 全部厂区
            $list = $infoModel
                ->field("*, 0 as sum")
                ->where('status' ,'eq', '已通过' )
                ->where($where)
                ->select();

            $infos = array_column( Collection($list)->toArray() , null, 'info_id');
            //print_r($infos); die;
            //  todo  优化计算方法
            foreach($list as $k => $v){
                $infos[ $v['info_id'] ]['sum'] += $v['nums'];
                //$infos[ $v['info_id'] ]['factory_id'] = '-';
            }
        }

//        print_r($infos); die;
//        $infos = $this->getXXX($infos);

        $row = array_values($infos);
        $result = ['total' => '', 'rows' => $row ];
        return json($result);
    }


}
